package au.com.betaversion.tmdb;

import java.net.URL;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TMDbClient {
	
	private static final Logger logger = LoggerFactory.getLogger(TMDbClient.class);

	private final String baseUrl = "http://api.themoviedb.org/";
	private final String apiKey;
	protected final ObjectMapper mapper;
	
	public TMDbClient(String apiKey) {
		super();
		this.apiKey = apiKey;
		mapper = new ObjectMapper();
	}
	
	public Map<?, ?> getMovie(String movieId) {
		try {
			List<?> list = mapper.readValue(new URL(buildMovieUrl(movieId)), List.class);
			return (Map<?, ?>)list.get(0);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}		
	}
	
	public List<?> getTop10() {
		try {
			String top10Url = buildRatingUrl();
			logger.info("Top 10 URL: " + top10Url);
			List<?> list = mapper.readValue(new URL(top10Url), List.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}		
	}
	
	public List<?> search(String title) {
		try {
			String searchUrl = buildSearchUrl(title);
			logger.info("Search URL " + searchUrl);
			List<?> list = mapper.readValue(new URL(searchUrl), List.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}		
	}

	private String buildSearchUrl(String title) {
		return baseUrl + "2.1/Movie.search/en/json/" + apiKey +"/" + title.replace(" ", "+");
	}
	
	private String buildRatingUrl() {
		return baseUrl + "2.1/Movie.browse/en/json/" + apiKey +"?order_by=rating&order=desc&per_page=10";
	}
	
	private String buildMovieUrl(String movieId) {
		return baseUrl + "2.1/Movie.getInfo/en/json/" + apiKey +"/" + movieId;
	}
}
